package org.basis.algorithm.graph;

import org.basis.algorithm.graph.common.Edge;
import org.basis.algorithm.graph.common.Graph;
import org.basis.algorithm.graph.common.Node;

/**
 * 图生成
 *
 * @author Mr_wenpan@163.com 2021/12/22 21:34
 */
public class GraphGenerator {

    public static void main(String[] args) {

    }

    /**
     * 练习图的通用模板使用
     * 用户给定你一个二维数组，将这个二维数组用图来表示
     * matrix 为 m * 3 的矩阵，matrix[m][0] 为：边的权值 matrix[m][1] 为：边的from节点的值 matrix[m][2] 为：边的to节点的值
     */
    public static Graph createGraph(Integer[][] matrix) {
        Graph graph = new Graph();
        for (Integer[] ma : matrix) {
            Integer weight = ma[0];
            Integer from = ma[1];
            Integer to = ma[2];
            if (!graph.nodes.containsKey(from)) {
                Node fromNode = new Node(from);
                graph.nodes.put(from, fromNode);
            }
            if (!graph.nodes.containsKey(to)) {
                Node toNode = new Node(to);
                graph.nodes.put(to, toNode);
            }
            // 构建边
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            Edge edge = new Edge(fromNode, toNode, weight);
            graph.edges.add(edge);

            // 构建点的出度入度，以及点的边集合
            fromNode.edges.add(edge);
            fromNode.out++;
            toNode.in++;
            // fromNode的直接相邻的节点
            fromNode.nexts.add(toNode);
        }

        return graph;
    }
}
